package crawler.client.core.handle;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import crawler.utility.crypto.CryptoUtil;
import crawler.utility.date.TimeUtility;
import crawler.utility.file.FileOperation;

@Service
public class IDHandle {
	
	private static Logger log = LoggerFactory.getLogger(IDHandle.class);
	
	@Autowired
	private PathHandle pathHandle;
	
	public String getClientId() {
		
		long currentTime = TimeUtility.getCurrentLongTime();
		
		String current = TimeUtility.getLongToString(currentTime, TimeUtility.FORMATTER_LONG);
		String id = CryptoUtil.getMD5(current);

		JSONObject fileJSON = new JSONObject();
		fileJSON.put("id", id);
		fileJSON.put("currentTime", currentTime);

		
		String filein = fileJSON.toJSONString() + FileOperation.LINE_SEPARATOR;// 新写入的行+换行
		
		try {

			String pathName = pathHandle.getBasePath() + "/id.properties";
			FileOperation fileOperation = new FileOperation(pathName);
			
			if (!fileOperation.exists()) {
				
				fileOperation.createContentFile(filein);

				log.info("Create ID : " + id);
			} else {
				
				id = fileOperation.readContentFile();
				
				log.info("Get Exists ID : " + id);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("getClientId Error : " ,e);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("getClientId Error : " ,e);
		}

		return id;
	}
}
